package com.tdcy.framework.dao.metadata;

import java.sql.Connection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.tdcy.framework.exception.BaseException;

/**
 * 业务SQL映射.
 * 
 */
public abstract class MetaDataMapping {
	/** The Constant tables. */
	private static final Map<String, TableMetadata> tables = new ConcurrentHashMap<String, TableMetadata>();

	/** The _size. */
	private static int _size = 0;

	/** The _times. */
	private static int _times = 0;

	/** The _lock. */
	private static Object _lock = new Object();

	/**
	 * Instantiates a new dB sql mapping.
	 */
	private MetaDataMapping() {

	}

	/**
	 * 获取表结构对象.
	 * 
	 * @param tableName
	 *            表名
	 * @return 表结构对象
	 * @throws BaseException
	 *             the exception
	 */
	public static TableMetadata getTableMetaData(Connection conn,String tableName) throws BaseException {
		String name = tableName.toUpperCase();
		TableMetadata tmd = tables.get(name);

		if (tmd == null) {
			DatabaseMetadata meta = new DatabaseMetadata(conn);
			String catalog = null;
			String schema = "";
			tmd = meta.getTableMetadata(catalog, schema, name);
			tables.put(name, tmd);

			_size = tables.size();
		}

		return tmd;
	}

	/**
	 * 刷新映射缓存.
	 * 
	 * @throws BaseException
	 *             the exception
	 */
	public static void refresh() throws BaseException {
		synchronized (_lock) {
			tables.clear();

			// 记录数
			_size = 0;
			_times++;
		}
	}

	/**
	 * 初始化.
	 * 
	 * @throws BaseException
	 *             the exception
	 */
	public static void init() throws BaseException {
		refresh();
	}

	/**
	 * 获取映射的大小.
	 * 
	 * @return the size
	 */
	public static int getSize() {
		return _size;
	}

	/**
	 * 获取刷新次数.
	 * 
	 * @return 刷新次数
	 */
	public static int getTimes() {
		return _times;
	}
}